#include "miscellaneous.h"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#pragma comment (lib, "glu32.lib")
#pragma comment (lib, "openGL32.lib")


#include "GLCanvas.h"

#define WIN_WIDTH 800
#define WIN_HEIGHT 600
#define NUM_PBO 3

GLCanvas canvas;

void updateData(unsigned char* data, int w, int h, int bpp) 
{
    for (int i = 0; i < h; ++i)
    {
        for (int j = 0; j < w; ++j)
        {
            int pos = i * w + j;
            if (((i / 3)*(j / 3)) % 24)
            {
                data[bpp * pos] = 255;
                data[bpp * pos + 1] = 0;
                data[bpp * pos + 2] = 0;
            }
            else 
            {
                data[bpp * pos] = 255;
                data[bpp * pos + 1] = 255;
                data[bpp * pos + 2] = 0;
            }
            data[bpp * pos + 3] = 255;
        }
    }
}

void resize(GLFWwindow* win, int w, int h) 
{
    if (!win) return;
    glfwMakeContextCurrent(win);
    canvas.resize(w, h);
}

int main()
{
    auto glfwError = glfwInit();
    if (GLFW_TRUE != glfwError) {
        CPrintLine("GLFW init ERROR!", enmCFC_Red);
        return 0;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow * window = glfwCreateWindow(WIN_WIDTH, WIN_HEIGHT, "draw pixels", nullptr, nullptr);
    if (nullptr == window) {
        CPrintLine("Create GLFW Window Failed!", enmCFC_Red);
        glfwTerminate();
        return 0;
    }

    glfwMakeContextCurrent(window);

    auto glewError = glewInit();
    if (GLEW_OK != glewError) {
        CPrintLine("GLEW init ERROR!", enmCFC_Red);
        return 0;
    }
    
    glfwSwapInterval(0);

    canvas.init(WIN_WIDTH, WIN_HEIGHT, NUM_PBO);
    glfwSetWindowSizeCallback(window, resize);

    Timer timer;
    char title[256];

    while (!glfwWindowShouldClose(window)) 
    {

        updateData(&canvas.pixels()[0], canvas.width(), canvas.height(), canvas.bytesPerPixel());
        canvas.dirty();

        timer.start();

        canvas.render();

        timer.end();

        glfwSwapBuffers(window);

        glfwPollEvents();


        sprintf(title, "%.1f", timer.time_ms());
        glfwSetWindowTitle(window, title);
    }
    
    canvas.release();

    glfwTerminate();

    return 0;
}
